package com.lyons.easyweb.modular.timer.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.lyons.easyweb.exception.BaseResponseCode;
import com.lyons.easyweb.exception.BusinessException;
import com.lyons.easyweb.modular.timer.dao.TimersMapper;
import com.lyons.easyweb.modular.timer.pojo.Timers;
import com.lyons.easyweb.modular.timer.service.TimerExeService;
import com.lyons.easyweb.modular.timer.service.TimerTaskRunner;
import com.lyons.easyweb.modular.timer.service.TimersService;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.extra.spring.SpringUtil;

/**
 * <p>
 * 定时任务 服务实现类
 * </p>
 *
 * @author Lyons
 * @since 2021-07-12
 */
@Service
public class TimersServiceImpl extends ServiceImpl<TimersMapper, Timers> implements TimersService {

	@Autowired
	private TimerExeService timerExeService;

	public List<String> getActionClasses() {

		List<String> list = Lists.newArrayList();

		Map<String, TimerTaskRunner> timerTaskRunnerMap = SpringUtil.getBeansOfType(TimerTaskRunner.class);
		if (ObjectUtil.isNotEmpty(timerTaskRunnerMap)) {

			Collection<TimerTaskRunner> values = timerTaskRunnerMap.values();
			for (TimerTaskRunner ttr : values) {

				String name = ttr.getClass().getName();
				list.add(name);
			}
		}

		return list;
	}

	@Override
	public boolean status(String id, boolean status) {

		Timers bean = this.getById(id);
		if (ObjectUtils.isEmpty(bean)) {
			throw new BusinessException(BaseResponseCode.DATA_ID_EMPTY);
		}
		if (status) {

			bean.setJobStatus(1);
			timerExeService.startTimer(bean.getId(), bean.getCron(), bean.getActionClass());
		} else {

			bean.setJobStatus(2);
			timerExeService.stopTimer(bean.getId());
		}
		this.updateById(bean);

		return status;
	}

	@Override
	public void insertOrUpdate(Timers timers) {
		try {
			if (ObjectUtil.isEmpty(timers.getId())) {

				timers.setJobStatus(2);
				this.save(timers);
			} else {

				this.updateById(timers);

				if (timers.getJobStatus() == 1) {
					CronUtil.remove(String.valueOf(timers.getId()));
					timerExeService.startTimer(String.valueOf(timers.getId()), timers.getCron(), timers.getActionClass());
				}
			}
		} catch (Exception e) {
			e.getStackTrace();
		}
	}

}
